package com.skydoves.chatgpt.feature.chat.ddd.bots



import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.asLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import com.example.core_database.entities.User
import com.example.core_database.entities.Bot
import com.example.core_database.database.AppDatabase
import com.skydoves.chatgpt.feature.chat.ddd.users.UserRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import okhttp3.internal.wait
import javax.inject.Inject


@HiltViewModel
class BotsViewModel@Inject constructor(
  application: Application,
  private val uidFlow: Flow<String>,
) : AndroidViewModel(application) {
  private val botRepository: BotRepository
  private val userRepository: UserRepository
  val allBots: LiveData<List<Bot>>
  private val _user = MutableLiveData<User?>()
  val user: LiveData<User?> = _user
  var Uid :String=" "


  init {
    val botDao = AppDatabase.getDatabase(application).botDao()
    val userDao = AppDatabase.getDatabase(application).userDao()

    userRepository = UserRepository(userDao)

    loadUser()
    botRepository = BotRepository(botDao)
    //Log.i("userIddd",uidFlow.firstOrNull()?)
    allBots = botRepository.allBots.asLiveData() // 将 Flow 转换为 LiveData
  }

  private fun loadUser() {
    viewModelScope.launch {


      val userId = uidFlow.firstOrNull() ?: return@launch
      Uid=userId


      Log.i("AppUser",userId)

      val existingUser = userRepository.getUserById(userId)
      if (existingUser == null) {
        // 如果没有找到用户，创建一个新用户
        Log.i("AppUser","can't find${userId},create a new User")
        val newUser = User(
          userId = userId,
          userNickname = "未命名",
          preference = " 该用户尚未填写简介",
          head = "https://user-images.githubusercontent.com/24237865/206655413-fb7c70f6-703e-476b-9ee9-861bfb8bf6f7.jpeg"
        )
        userRepository.insert(newUser)
        _user.postValue(newUser)
      } else {
        Log.i("AppUser","find successfull: ${userId}")
        _user.postValue(existingUser)
      }
    }
  }

  fun insert(bot: Bot) = viewModelScope.launch {
    botRepository.insert(bot)
    //Log.d("BotsViewModel", "Bot inserted: ${bot.botName}")
  }

  fun delete(bot: Bot) = viewModelScope.launch {
    botRepository.delete(bot)
  }
}
